<template>
  <div class="basics-form">
    <div v-if="flag" class="basics-form-wrap">
      <div :class="[
          'basics-form-item',
          item.type == 'title' ? 'basics-form-title' : '',
        ]" :style="{
          width: item.ruleWidth,
          minWidth: item.type == 'actionBtns' ? '0px' : minWidth,
        }" v-for="(item, index) in rules" :key="'item' + index" v-show="!item.hidden">
        <slot name="rule" :slotKey="item.name" :slotData="slotData" v-if="item.type == 'slot'"></slot>
        <h2 v-else-if="item.type == 'title'">{{ item.title }}</h2>
        <div v-else-if="item.type == 'actionBtns'" :style="{ display: 'flex', justifyContent: item.btnsAligin }">
          <el-button @click="$emit('actionBtnsClick', ind)" v-for="(it, ind) in item.selectListTemp" :key="ind"
            :type="it.value" :loading="actionLoading || actionLoading2">{{ it.name }}</el-button>
        </div>
        <div v-else class="basics-form-item-content">
          <!-- 左侧标题 -->
          <div class="basics-form-item-content-label" :style="{
              width: item.titleWidth || titleWidth,
              textAlign: item.titleAligin || titleAligin,
              whiteSpace: !item.titleWidth && !titleWidth ? 'nowrap' : '',
            }">
            <span v-if="!hiddenMustIcon && !item.skip" class="must">*</span>
            {{ item.title }}：
          </div>
          <!-- 加入自定义内容，插槽 ，slotOrder=3？左侧 ：右侧-->
              <div
                :style="{
                  order: item.slotOrder
                    ? item.slotOrder == 'left'
                      ? 1
                      : 3
                    : hiddenTitle
                    ? 3
                    : 1,
                }"
                style="line-height: 40rpx"
              >
                <slot
                  name="inside"
                  :ruleKey="item.name"
                  :slotData="slotData"
                ></slot>
              </div>
          <!-- 内容 -->
          <div :style="{
            order:2,
              flexGrow: 2,
              width:item.contentWidth?item.contentWidth:
                item.titleWidth || titleWidth
                  ? `calc(100% - ${item.titleWidth || titleWidth})`
                  : '',
            }">
            <!-- 文字 数字 文本域 密码-->
            <el-input v-if="
                item.type == 'text' ||
                item.type == 'Number' ||
                item.type == 'textarea' ||
                item.type == 'password'"
                :style="{width:item.contentWidth||''}"
               @blur="itemValid(item, index)"
              :show-password="item.type == 'password'" :maxlength="item.maxlength"
              :disabled="item.disabled || showActionSheet" :type="item.type || 'text'"
              :password="item.password && !showPassword" v-model="param[item.name]" :name="item.name"
              :placeholder="item.placeholder" clearable />

            <!-- 单选radio -->
            <div v-else-if="item.type == 'radio'" style="padding: 10px 0" class="basics-form-item-error">
              <el-radio-group v-model="param[item.name]">
                <el-radio v-for="(it, ind) in item.selectList" :key="'it' + ind" :label="ind">{{ it }}</el-radio>
              </el-radio-group>
            </div>
            <!-- 选择器 -->
            <div v-else-if="
                item.type == 'select' ||
                item.type == 'choose' ||
                item.type == 'tabSelect'
              " style="display: flex">
              <div v-if="item.type == 'tabSelect'" style="padding: 10px 0; flex-grow: 2; margin-top: -20px"
                class="basics-form-item-error">
                <el-checkbox :indeterminate="true" v-model="item.checkAll" @change="checkAllChange(item, index)">
                  {{ item.checkAll ? "取消" : "" }}全选</el-checkbox>
                <el-checkbox-group v-model="param[item.name]" @change="itemValid(item, index)">
                  <el-checkbox v-for="(it, ind) in item.selectList" :label="ind" :key="ind">{{ it.name }}</el-checkbox>
                </el-checkbox-group>
              </div>

              <el-select v-else filterable style="flex-grow: 2" :clearable="!item.hiddenClose"
                :multiple="item.type == 'choose'" v-model="param[item.name]" :placeholder="item.placeholder"
                @change="itemValid(item, index,true,true)">
                <el-option v-for="(it, ind) in item.selectList" :key="ind" :label="it.name" :value="ind"
                  :disabled="it.disabled" :placeholder="item.placeholder">
                </el-option>
              </el-select>
              <!-- 选择器自定义输入 -->
              <div style="max-width: 40%" v-if="item.selectInputKey && item.selectInputByIndex > -1">
                <el-input clearable style="margin-left: 10px; width: calc(100% - 10px)" @blur="itemValid(item, index)"
                  @change="itemValid(item, index)" v-if="
                    (item.type == 'select' &&
                      param[item.name] == item.selectInputByIndex) ||
                    ((item.type == 'choose' || item.type == 'tabSelect') &&
                      param[item.name] &&
                      param[item.name].indexOf(item.selectInputByIndex) > -1)
                  " v-model="param[item.selectInputKey]" :placeholder="
                    '请输入' + item.selectList[item.selectInputByIndex].name
                  " />
              </div>
            </div>
            <!-- 级联选择器 -->
            <div v-else-if="item.type == 'cascader'">
              <el-cascader v-model="param[item.name]" :placeholder="item.placeholder" :options="item.selectList"
                filterable style="width: 100%" clearable :props="item.cascaderProps" @change="itemValid(item, index)">
              </el-cascader>
            </div>
            <!-- 时间 -->
            <el-date-picker v-else-if="
                item.type == 'selectDate' ||
                item.type == 'datetime' ||
                item.type == 'daterange' ||
                item.type == 'year'
              " @change="itemValid(item, index)" v-model="param[item.name]"
              :type="item.type == 'selectDate' ? 'date' : item.type" :placeholder="item.placeholder" style="width: 100%"
              start-placeholder="开始日期" end-placeholder="结束日期" :value-format="
                item.type == 'year'
                  ? `yyyy`
                  : `yyyy-MM-dd${item.type == 'datetime' ? ' HH:mm:ss' : ''}`
              " />
            <!-- 范围，数字 -->
            <div v-else-if="item.type == 'numberRange'">
              <el-input @blur="itemValid(item, index)" @change="itemValid(item, index)" :maxlength="item.maxlength"
                :disabled="item.disabled || showActionSheet" type="Number" :password="item.password && !showPassword"
                v-model="param[item.name]" :name="item.name" :placeholder="item.numberRangePlaceholder[0]" clearable
                style="width: calc(50% - 24px)" />
              <span style="padding: 0 20px; line-height: 40px">-</span>
              <el-input @blur="itemValid(item, index)" @change="itemValid(item, index)" :maxlength="item.maxlength"
                :disabled="item.disabled || showActionSheet" type="Number" :password="item.password && !showPassword"
                v-model="param[item.rangeKey]" :name="item.name" :placeholder="item.numberRangePlaceholder[1]" clearable
                style="width: calc(50% - 24px)" />
            </div>
            <!-- 图片上传 -->
            <div v-else-if="item.type == 'img'" style="margin-top: 6px">
              <el-upload :ref="item.name" :action="item.uploadAction || uploadAction" class="avatar-uploader"
                :show-file-list="false"  :multiple="false" :file-list="fileList[item.name]" :auto-upload="item.autoUpload" :headers="headers" :data="item.uploadExtra" :on-change="
                  (r, f) => {
                    handleFileChange(r, f, item.name,index);
                  }
                " :on-success="
                  (r, f) => {
                    uploadSuccess(r, f, item.name, item.title);
                  }
                "
                >
                <img v-if="param[item.name]" :src="param[item.name]" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div v-if="param[item.name]" style="text-align: center; width: 178px">
                <span style="color: #2baee9; cursor: pointer"
                  @click="handlePictureCardPreview(param[item.name])">预览</span><span
                  style="color: red; margin-left: 40px; cursor: pointer" @click="()=>{param[item.name] = '';$refs[item.name][0].clearFiles()} ">删除</span>
              </div>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </div>
            <!-- 文件上传 -->
            <div v-else-if="item.type == 'file'" style="margin-top: 6px">
              <el-upload :ref="item.name" class="upload-demo" :action="item.uploadAction || uploadAction"
                :auto-upload="item.autoUpload" :limit="1"  :multiple="false" :file-list="fileList[item.name]" :headers="headers" :data="item.uploadExtra" :show-file-list="false" :on-change="
                  (r, f) => {
                    handleFileChange(r, f, item.name, index);
                  }
                " :on-success="
                  (r, f) => {
                    uploadSuccess(r, f, item.name, item.title);
                  }
                " :on-remove="
                  () => {
                    param[item.name] = '';
                  }
                ">
                <el-button size="small" type="primary">点击选择</el-button>
                <div v-if="item.fileTypes" slot="tip" class="el-upload__tip">
                  只能上传{{ item.fileTypes.jion("/") }}文件
                </div>
              </el-upload>
              <div v-if="param[item.name]">
                {{ item.fileName || param[item.name] }}
              </div>
              <span v-if="param[item.name]" style="color: red; margin-top: 6px; cursor: pointer"
                @click="()=>{param[item.name] = '';$refs[item.name][0].clearFiles()} ">删除</span>
            </div>
            <!-- 纯文字显示 -->
            <div v-else-if="item.type == 'string'" style="margin-top: 6px">
              {{ param[item.name] }}
            </div>
            <div class="basics-form-item-error-msg">{{ item.errorMsg }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import form from "./tui-validation.js";
  import {
    getToken
  } from "@/utils/auth";
  export default {
    components: {},
    props: {
      hiddenMustIcon: {
        //隐藏必填*号
        type: Boolean,
        default: false,
      },
      minWidth: {
        //最小宽度
        type: String,
        default: "503px",
      },
      slotData: {
        type: Object,
        default: () => {},
      },
      showPassword: {
        //是否显示密码
        type: Boolean,
        default: false,
      },
      hiddenTitle: {
        //隐藏标题模式
        type: Boolean,
        default: false,
      },
      actionLoading: {
        //操作按钮loding
        type: Boolean,
        default: false,
      },
      immediatelyValid: {
        //立即校验
        type: Boolean,
        default: false,
      },
      titleWidth: {
        //全局标题宽度
        type: String,
        default: "",
      },
      titleAligin: {
        //全局标题位置
        type: String,
        default: "left",
      },
      uploadAction: {
        //文件上传地址
        type: String,
        default: "",
      },
    },
    watch: {
      // param: {
      //   handler(new_value, old_value) {
      //     // this.formValid(0, false)
      //     return;
      //     if (this.immediatelyValid) {
      //       this.formValid(0, false);
      //     }
      //   },
      //   deep: true,
      // },
    },
    data() {
      return {
        flag:false,
        rules: [],
        headers: {
          Authorization: "Bearer " + getToken(),
          roleId: sessionStorage.getItem("roleId"),
        },
        actionLoading2: false, //上传图片loading
        value: 0,
        param: {},
        showActionSheet: false,
        ruleindex: -1,
        disabled: true,
        goBack: false,
        choose: false, //多选
        dialogVisible: false,
        dialogImageUrl: "",
        imgKeys: [], //要上传的图片key
        submitParam: {}, //要提交的数据
        fileList:{},//要上传的文件
      };
    },
    created(options) {},
    methods: {
      //构建表单  选择器类型的value传下标 或 下标的list
      initForm(rules) {
        this.flag=false
        this.rules = [];
        this.param = {};
        this.fileList = {};
        rules.forEach((item, index) => {
          let placeholder = "请输入",
            selectTypes = [
              "address",
              "select",
              "choose",
              "selectDate",
              "datetime",
              "daterange",
              "tabSelect",
              "img",
              "file",
              "radio",
              "cascader",
            ];
          if (selectTypes.indexOf(item.type) > -1) {
            placeholder = "请选择";
          }
          if (!item.title) {
            item.title = "";
          }
          let ruleItem = {
            name: item.key || item.slotKey || "",
            type: item.type == "number" ? "Number" : item.type || "text", //类型

            ruleWidth: item.ruleWidth || "", //宽度，pc端才有
            skip: item.type == "title" || item.type == "actionBtns" ?
              false :
              item.skip || false, //不必填
            rule: item.skip ?
              item.ruleList || [] :
              ["required"].concat(item.ruleList || []), //校验规则
            msg: item.skip ?
              item.ruleMsgList || []
            : [placeholder + item.title].concat(item.ruleMsgList || []), //校验规则的提示语句

            bottomSeparate: item.bottomSeparate || false, //底部分隔效果
            hidden: item.hidden || false, //隐藏该item, 也不校验
            leftIocn: item.leftIocn || false, //左侧图标

            addressDetailsKey: item.addressDetailsKey || "", //地址详情字段
            addressCoordinateKey: item.addressCoordinateKey || "", //地址坐标字段
            hiddenClose: item.hiddenClose || false, //是否隐藏清空按钮
            slotOrder: item.slotOrder && item.slotOrder > -1 ? item.slotOrder : -1,

            validFunc: item.validFunc, //需要进行传入的方法校验
            customValid: item.customValid || false, //是否需要返回父组件进行校验
            hideSecond: item.hideSecond || false, //type=selectDateTime时，是否隐藏 秒
            cascaderProps: item.cascaderProps || {}, //级联选择配置
            numberRangePlaceholder: item.type == "numberRange" ?
              item.numberRangePlaceholder || ["起始", "结束"] :
              false,
            rangeKey: item.rangeKey || "",
            placeholder: item.disabled && !item.placeholder ?
              "" :
              item.placeholder || placeholder,

            password: item.type == "password" ? true : false,
            tips: item.tips,
            title: item.title,
            titleWidth: item.titleWidth || "",
            titleAligin: item.titleAligin || "",
            titleColor: item.titleColor || false,
            maxlength: item.maxlength || 300,
            disabled: item.disabled || false,
            itemClick: item.itemClick || false, //item点击事件是否回调
            callback: item.callback || false, //选择器是否实时回调
            selectKey: item.selectKey || false, //选择器返回的key  //默认是下标
            selectShowKey: item.selectShowKey || false, //选择器显示的key  //默认name
            showFilter: item.showFilter || false, //选择器能否筛选
            selectOrigin: item.selectOrigin || false, //选择器是否返回原始数据 开启后selectKey无效
            selectListTemp: item.selectList, //保存原始选项数据

            autoUpload: item.autoUpload || false, //文件上传地址
            uploadAction: item.uploadAction || "", //文件上传地址
            submitInUpload: item.submitInUpload || false, //数据与文件一起上传
            uploadExtra: item.uploadExtra || {}, //文件上传额外参数
            fileTypes: item.fileTypes || null, //上传文件类型限制
            fileName: item.fileName || null, //文件名称

            btnsAligin: item.btnsAligin || "", //操作按钮位置，左中右等等
            contentWidth: item.contentWidth || false,
            hiddenBorderBottom: item.hiddenBorderBottom || false, //隐藏下划线
            showRightArrow: item.showRightArrow || false, //输入类型也显示右箭头
            maxSelectCount: item.maxSelectCount || 10000000, //最大选择个数，目前之适用于type=tabSelect
            selectInputByIndex: item.selectInputByIndex || -1, //选择器选择某个下标后需要输入自定义内容
            selectInputKey: item.selectInputKey || false, //接受自定义内容的字段
            selectInputRuleList: item.selectInputByIndex > -1 ?
              ["required"].concat(item.selectInputRuleList || []) :
              [],
            selectInputRuleMsgList: item.selectInputByIndex > -1 ?
              [
                "请输入" + item.selectList[item.selectInputByIndex].name,
              ].concat(item.selectInputRuleMsgList || []) :
              [],
          };

          if (item.type != "cascader") {
            let selectList = [];
            if (item.selectList && item.selectList.length) {
              item.selectList.forEach((it, ind) => {
                if (typeof it != "object") {
                  if (item.type == "radio") {
                    selectList.push(it);
                  } else {
                    selectList.push({
                      name: it
                    });
                  }
                } else {
                  let name = item.selectShowKey ?
                    it[item.selectShowKey] :
                    it.name || "";
                  if (item.type == "radio") {
                    selectList.push(name);
                  } else {
                    selectList.push({
                      name
                    });
                  }
                }
              });
            }
            ruleItem.selectList = selectList; //选择器选择时展示用
          } else {
            ruleItem.selectList = item.selectList; //级联选择器选择时展示用
          }
          if (item.key && item.type != "title") {
            this.param[item.key] =
              item.value != undefined ?
              item.value :
              item.type == "choose" ||
              item.type == "checkbox" ||
              item.type == "tabSelect" ||
              item.type == "daterange" ?
              [] :
              "";
          }
          if (item.type == "numberRange") {
            this.param[item.rangeKey] =
              item.rangeValue != undefined ? item.rangeValue : "";
          }
          if (item.selectInputByIndex > -1 && item.selectInputKey) {
            this.param[item.selectInputKey] =
              item.selectInputValue != undefined ? item.selectInputValue : "";
          }

          this.rules.push(ruleItem);
        });
        this.param = JSON.parse(JSON.stringify(this.param));
        this.flag=true
      },
      //表单重置 暂无法触发选择器回调
      formReset() {
        for (let key in this.param) {
          this.param[key] = null;
        }
      },
      //表单验证
      formValid(start = 0, submit = true) {
        if (!start) {
          start = 0;
        }
        if (start >= this.rules.length) {
          if (submit) {
            this.formSubmit();
          }
          return;
        }
        console.log(start, this.rules, "----");
        let validError = false;
        this.rules.forEach((item, index) => {
          if (!item.name || item.hidden) {
            let temp = this.rules[index];
            temp.errorMsg = "";
            this.$set(this.rules, index, temp);
            return true;
          }
          let ve = false;
          if (index >= start) {
            ve = this.itemValid(item, index, submit, false);
          }
          if (!validError) {
            validError = ve;
          }
        });
        if (validError) {
          console.log("检验error");
          if (!submit) {
            this.$emit("validValue", false, this.param);
          }
        } else {
          console.log("检验success");
          if (submit) {
            this.formSubmit();
          } else {
            this.$emit("validValue", true, this.param);
          }
        }
      },
      checkAllChange(item, index) {
        let list = [];
        if (item.checkAll) {
          item.selectList.forEach((it, ind) => {
            list.push(ind);
          });
        }
        this.param[item.name] = list;
        this.itemValid(item, index);
      },
      itemValid(item, index, submit = true, callback = true) {
        if (callback && item.callback) {
          this.$emit("selectCallback", {
            key: item.name,
            value:item.selectKey?item.selectListTemp[this.param[item.name]][item.selectKey]:
            item.selectOrigin?item.selectListTemp[this.param[item.name]]:this.param[item.name],
            index: index,
          });
        }
        let tempRule = this.rules[index];
        tempRule.errorMsg = "";
        this.$set(this.rules, index, tempRule);
        let tempParam = JSON.parse(JSON.stringify(this.param));
        let checkRes = null;
        if (item.type == "slot" && !this.skip) {
          if (item.validFunc) {
            checkRes = item.validFunc(tempParam);
          }
          if (checkRes) {
            if (submit) {
              tempRule.errorMsg = checkRes;
              this.$set(this.rules, index, tempRule);
            }
            return true;
          }
          // else if (item.customValid) {
          //   this.$emit("customValid", {
          //     rule: item,
          //     data: tempParam,
          //     index,
          //   });
          //   return false;
          // }
        } else {
          let temp = JSON.parse(JSON.stringify(item));
          if (temp.skip) {
            if (temp.rule.length && temp.rule[0] == "required") {
              temp.rule = temp.rule.splice(0, 1);
              temp.msg = temp.rule.splice(0, 1);
            }
          }
          let param = {};
          if (Array.isArray(tempParam[item.name])) {
            tempRule.checkAll =
              tempParam[item.name].length == item.selectList.length;
            this.$set(this.rules, index, tempRule);
            param[item.name] =
              tempParam[item.name] != undefined && tempParam[item.name] != null ?
              tempParam[item.name].length || "" :
              "";
          } else {
            param[item.name] =
              tempParam[item.name] != undefined && tempParam[item.name] != null ?
              tempParam[item.name] + "" :
              "";
          }
          if (!item.skip && item.numberRangePlaceholder) {
            temp.msg[0] =
              item.placeholder +
              item.title +
              " - " +
              item.numberRangePlaceholder[0];
          }
          checkRes = form.validation(param, [temp], !submit);
          if (checkRes && (item.type == "Number" || item.type == "numberRange")) {
            //重置数字
            this.param[item.name] = 0;
            this.$nextTick(() => {
              this.param[item.name] = "";
            });
          }
          if (!checkRes && item.type == "numberRange") {
            param = {};
            param[item.rangeKey] = tempParam[item.rangeKey];
            temp.name = item.rangeKey;
            if (!item.skip && item.numberRangePlaceholder) {
              temp.msg[0] =
                item.placeholder +
                item.title +
                " - " +
                item.numberRangePlaceholder[1];
            }
            checkRes = form.validation(param, [temp], !submit);
            if (checkRes) {
              //重置数字
              this.param[item.rangeKey] = 0;
              this.$nextTick(() => {
                this.param[item.rangeKey] = "";
              });
            }
            if (
              !checkRes &&
              tempParam[item.name] &&
              tempParam[item.rangeKey] &&
              Number(tempParam[item.rangeKey]) <= Number(tempParam[item.name])
            ) {
              checkRes =
                temp.title +
                "的" +
                item.numberRangePlaceholder[1] +
                "必须大于" +
                item.numberRangePlaceholder[0];
            }
          }
          if (
            !checkRes &&
            item.selectInputByIndex > -1 &&
            item.selectInputKey &&
            ((item.type == "select" &&
                tempParam[item.name] == item.selectInputByIndex) ||
              ((item.type == "choose" || item.type == "tabSelect") &&
                tempParam[item.name].indexOf(item.selectInputByIndex) > -1))
          ) {
            let param = {};
            param[item.selectInputKey] = tempParam[item.selectInputKey];
            temp.skip = false;
            temp.name = item.selectInputKey;
            temp.rule = item.selectInputRuleList;
            temp.msg = item.selectInputRuleMsgList;
            checkRes = form.validation(param, [temp], !submit);
          }
          if (!checkRes && item.validFunc) {
            checkRes = item.validFunc(tempParam);
          }
          if (checkRes) {
            if (submit) {
              tempRule.errorMsg = checkRes;
              this.$set(this.rules, index, tempRule);
            }
            return true;
          }
          //  else if (item.customValid) {
          //   this.$emit("customValid", {
          //     rule: item,
          //     data: tempParam,
          //     index,
          //   });
          //   return true;
          // }
          return false;
        }
      },
      //修改rule某个属性的值
      changeRulesValue(data) {
        data.forEach((item) => {
          if (item.key == "selectList") {
            let selectList = [];
            if (item.value && item.value.length) {
              item.value.forEach((it, ind) => {
                if (typeof it != "object") {
                  if (item.type == "radio") {
                    selectList.push(it);
                  } else {
                    selectList.push({
                      name: it
                    });
                  }
                } else {
                  let name = this.rules[item.index].selectShowKey ?
                    it[this.rules[item.index].selectShowKey] :
                    it.name || "";
                  if (this.rules[item.index].type == "radio") {
                    selectList.push(name);
                  } else {
                    selectList.push({
                      name
                    });
                  }
                }
              });
            }
            this.rules[item.index].selectListTemp = item.value;
            this.rules[item.index][item.key] = selectList;
          } else {
            this.rules[item.index][item.key] = item.value;
          }
        });
      },
      //修改param某个属性的值
      changeParamValue(data) {
        this.param[data.key] = data.value;
        console.log( this.param[data.key],data.key)
      },
      //表单提交
      formSubmit() {
        let param = JSON.parse(JSON.stringify(this.param));
        this.rules.forEach((item) => {
          //处理选择器数据
          if (item.selectOrigin || item.selectKey) {
            //返回的数据 原始数据 ，对象key，否则下标
            if (item.type == "choose" || item.type == "tabSelect") {
              let chooseList = [];
              item.selectListTemp.forEach((it, index) => {
                if (param[item.name].indexOf(index) > -1) {
                  chooseList.push(item.selectOrigin ? it : it[item.selectKey]);
                }
              });
              param[item.name] = chooseList;
            } else if (
              item.type == "select" ||
              item.type == "switch" ||
              item.type == "radio"
            ) {
              item.selectListTemp.some((it, index) => {
                if (param[item.name] === index) {
                  param[item.name] = item.selectOrigin ? it : it[item.selectKey];
                  return true;
                }
              });
            }
          }
        });
        console.log(param, "数据");
        this.submitParam = param;
        //提交数据前上传文件
        this.uploadFile();
        // this.$emit("submit", param);
      },
      //打开选择弹窗
      openActionsheet(index, item) {
        this.ruleindex = index;
        this.$nextTick(() => {
          this.choose = item.type == "choose";
          this.showActionSheet = true;
        });
      },
      //item点击事件
      itemClick(item) {
        this.$emit("itemClick", {
          item,
          value: this.param[item.name]
        });
      },
      // beforeUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   const isPNG = file.type === "image/png";
      //   // const isLt2M = file.size / 1024 / 1024 < 2;
      //   if (!isJPG && !isPNG) {
      //     this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
      //   }
      //   // if (!isLt2M) {
      //   //   this.$message.error("上传头像图片大小不能超过 2MB!");
      //   // }
      //   return isJPG || isPNG;
      // },
      handleFileChange(res, fileList, key, index) {
        this.fileList[key]=[fileList[fileList.length-1]]
        console.log(fileList,'xxxxxxxxxxx');
        if (fileList.length) {
          this.param[key] = URL.createObjectURL(res.raw);
          if ( this.rules[index].type == "file") {
            this.rules[index].fileName = res.name;
          }
          if(this.rules[index].callback){
           this.$emit("selectCallback", {
             key: this.rules[index].name,
             value: res,
             index: index,
           });
          }
        } else {
          this.param[key] = "";
        }
      },

      //文件预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url || file;
        this.dialogVisible = true;
      },
      uploadFile() {
        this.imgKeys = [];
        this.rules.forEach((item) => {
          if (
            (item.type == "img" || item.type == "file") &&
            this.param[item.name] &&
            this.param[item.name].indexOf("blob") > -1
          ) {
            this.imgKeys.push(item.name);
            if (item.submitInUpload) {
              for (let key in this.submitParam) {
                item.uploadExtra[key] = this.submitParam[key];
              }
            }
          }
        });
        if (this.imgKeys.length) {
          this.param=JSON.parse(JSON.stringify(this.param))
          this.actionLoading2 = true;
          this.$refs[this.imgKeys[0]][0].submit();
        } else {
          this.$emit("submit", this.submitParam);
        }
      },

      uploadSuccess(res, file, key, title) {
        this.actionLoading2 = false;
        let index = this.imgKeys.indexOf(key);
        if (res.code == 200) {
          this.$nextTick(()=>{
            this.param[key] = res.data;
            this.submitParam[key] = res.data;
            if (index == this.imgKeys.length - 1) {
              this.$emit("submit", this.submitParam);
            } else {
              this.actionLoading2 = true;
              this.$refs[this.imgKeys[index + 1]][0].submit();
            }
          })
        } else {
          this.$modal.msgError(res.msg || title + "上传失败");
          this.$refs[this.imgKeys[index]][0].clearFiles();
        }
      },
    },
  };
</script>
<style lang="scss" scoped>
  .basics-form {
    width: 100%;
    overflow-x: hidden;
    ::v-deep .el-input.is-disabled .el-input__inner {
      color: #606266;
    }
    ::v-deep .el-textarea.is-disabled .el-textarea__inner {
      color: #606266;
    }

    &-wrap {
      display: flex;
      flex-wrap: wrap;
      margin-left: -60px;
    }

    &-item {
      // flex-grow: 1;
      width: 33.33%;
      // overflow-x:
      padding-left: 60px;
      box-sizing: border-box;
      // padding-right: 60px;
      margin-bottom: 4px;

      &-content {
        display: flex;
        flex-wrap: nowrap;

        &-label {
          padding: 9px 2px 0 0;
          box-sizing: border-box;

          .must {
            color: red;
          }
        }
      }

      &-error {
        ::v-deep .el-input__inner {
          border: 1px solid red;
        }
      }

      &-error-msg {
        width: 100%;
        color: red;
        font-size: 14px;
        height: 20px;
      }
    }

    &-title {
      width: 100%;
      border-bottom: 1px solid #dcdfe6;
      padding-bottom: 10px;

      h2 {
        border-left: 4px solid #2baee9;
        padding-left: 10px;
      }
    }

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader-icon {
      border: 1px dashed #d9d9d9;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
</style>
